package com.ccys.cms.service.masterData.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ccys.cms.service.masterData.PharmacyService;
import com.ccys.common.util.Kit;
import com.ccys.common.vo.ResponseResult;
import com.ccys.db.dto.masterData.PharmacyDto;
import com.ccys.db.entity.TblPharmacy;
import com.ccys.db.entity.TblPharmacyOperatingHours;
import com.ccys.db.mapper.TblPharmacyGroupMapper;
import com.ccys.db.mapper.TblPharmacyMapper;
import com.ccys.db.mapper.TblPharmacyOperatingHoursMapper;
import com.ccys.db.page.PageDto;
import com.ccys.db.rely.service.impl.BaseServiceImpl;
import com.ccys.db.service.BaseTblAuditTrailWebService;
import com.ccys.db.vo.masterData.PharmacyGroupQueryByCountryIdVo;
import com.ccys.db.vo.masterData.PharmacyPageQueryVo;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

/**
 * @program: WhiteCoat
 * @description: 药房接口实现类
 * @author: ZhangJingCan
 * @create: 2023-12-14 15:33
 **/

@Service
public class PharmacyServiceImpl extends BaseServiceImpl<TblPharmacy> implements PharmacyService {

    /**
     * 药房
     */
    @Resource
    private TblPharmacyMapper tblPharmacyMapper;

    /**
     * 药房营业时间
     */
    @Resource
    private TblPharmacyOperatingHoursMapper tblPharmacyOperatingHoursMapper;

    /**
     * 制药集团
     */
    @Resource
    private TblPharmacyGroupMapper tblPharmacyGroupMapper;

    /**
     * 用于保存修改状态日志
     */
    @Autowired(required = false)
    private BaseTblAuditTrailWebService baseTblAuditTrailWebService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult savePharmacy(PharmacyDto dto) {
        //校验字段
        Kit.allParamValid(dto, "groupId", "countryId", "type", "name", "phone", "email", "address", "pharmacist",
                "dispOrder", "latitude", "longitude", "postalCode", "collectionInstruction");
        //根据条件做不同校验
        if (dto.getType().equals(2)) {
            if (ObjectUtil.isEmpty(dto.getPharmacyGroupId())) {
                return ResponseResult.error("Parameter Error!");
            }
        }
        if (dto.getType().equals(3)) {
            if (ObjectUtil.isEmpty(dto.getClinicId())) {
                return ResponseResult.error("Parameter Error!");
            }
        }
        if (dto.getCollectionInstruction().equals(1)) {
            if (ObjectUtil.isEmpty(dto.getCollectionDay())) {
                return ResponseResult.error("Parameter Error!");
            }
        }
        //判断是新增还是修改
        if (ObjectUtil.isEmpty(dto.getId())) {
            //新增设置code
            //雪花算法生成code
            long code = IdUtil.getSnowflakeNextId();
            dto.setCode(code + "");
            //新增需要判断hours是不是有值 - 先新增本表数据 - 如果有值需要拿着本表返回的ID去生成hours表数据
            //先药房本表数据
            if (tblPharmacyMapper.insertSelective(dto) < 1) {
                return ResponseResult.error("Error in adding pharmacy data!");
            }
            //检查是否有值
            if (ObjectUtil.isNotEmpty(dto.getHours())) {
                //循环判断字段值
                for (TblPharmacyOperatingHours hour : dto.getHours()) {
                    //设置药房ID进数据
                    hour.setPharmacyId(dto.getId());
                    //校验字段
                    Kit.allParamValid(hour, "day", "startTime", "endTime");
                    tblPharmacyOperatingHoursMapper.insertSelective(hour);
                }
            }
        } else {
            //修改 - 同时操作药房营业时间
            tblPharmacyMapper.updateByPrimaryKeySelective(dto);
            //如果传入了营业时间 - 则操作
            if (ObjectUtil.isNotEmpty(dto.getHours())){
                //硬删除营业时间
                tblPharmacyOperatingHoursMapper.delByPharmacyId(dto.getId());
                //循环判断字段值
                for (TblPharmacyOperatingHours hour : dto.getHours()) {
                    //设置药房ID进数据
                    hour.setPharmacyId(dto.getId());
                    //校验字段
                    Kit.allParamValid(hour, "day", "startTime", "endTime");
                    tblPharmacyOperatingHoursMapper.insertSelective(hour);
                }
            }

        }
        return ResponseResult.success();
    }

    @Override
    public ResponseResult<PageInfo<PharmacyPageQueryVo>, Object> findPagePharmacy(PharmacyDto dto) {
        dto.setStatus(Optional.ofNullable(dto.getStatus()).filter(s -> s > -1 && s < 2).orElse(null));
        dto.setType(Optional.ofNullable(dto.getType()).filter(t -> t > 0 && t < 4).orElse(null));
        //开启分页
        PageDto.startPage();
        List<PharmacyPageQueryVo> list = tblPharmacyMapper.findPagePharmacy(dto);
        PageInfo<PharmacyPageQueryVo> info = new PageInfo<>(list);
        return ResponseResult.success(info);
    }

    @Override
    public ResponseResult<List<TblPharmacyOperatingHours>, Object> findListPharmacyOperatingHours(PharmacyDto dto) {
        //校验参数
        if (ObjectUtil.isEmpty(dto.getId())) {
            return ResponseResult.error("Parameter Error!");
        }
        //校验当前药房必须属于未删除 - 才去查询药房的营业时间集合数据
        Example pharmacyMapperExample = new Example(TblPharmacy.class);
        pharmacyMapperExample.createCriteria()
                .andEqualTo("id", dto.getId()).andEqualTo("delFlag", 0);
        if (ObjectUtil.isEmpty(tblPharmacyMapper.selectOneByExample(pharmacyMapperExample))) {
            return ResponseResult.error("illegal request");
        }
        Example hoursExample = new Example(TblPharmacyOperatingHours.class);
        hoursExample.createCriteria().andEqualTo("pharmacyId", dto.getId()).andEqualTo("delFlag", 0);
        return ResponseResult.success(tblPharmacyOperatingHoursMapper.selectByExample(hoursExample));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult deletePharmacy(PharmacyDto dto) {
        //校验参数
        if (ObjectUtil.isEmpty(dto.getId())) {
            return ResponseResult.error("Parameter Error!");
        }
        //准备参数进行软删除
        TblPharmacy tblPharmacy = new TblPharmacy();
        tblPharmacy.setId(dto.getId());
        tblPharmacy.setDelFlag(1);
        //进行操作并返回是否成功
        if (tblPharmacyMapper.updateByPrimaryKeySelective(tblPharmacy) > 0) {
            return ResponseResult.success("Delete Successful!");
        }
        return ResponseResult.error("Delete Failed!");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult updatePharmacyStatus(PharmacyDto dto) {
        if (ObjectUtil.isEmpty(dto.getId()) || ObjectUtil.isEmpty(dto.getStatus())) {
            return ResponseResult.error("Parameter Error!");
        }
        TblPharmacy tblPharmacy = new TblPharmacy();
        tblPharmacy.setId(dto.getId());
        tblPharmacy.setStatus(dto.getStatus());
        if (tblPharmacyMapper.updateByPrimaryKeySelective(tblPharmacy) > 0) {
            baseTblAuditTrailWebService.saveStatusLog(dto, dto.getStatus());
            return ResponseResult.success("Modified successfully!");
        }
        return ResponseResult.error("Modification failed!");
    }

    @Override
    public ResponseResult<List<PharmacyGroupQueryByCountryIdVo>, Object> findListPharmacyGroupByCountryId(PharmacyDto dto) {
        if (ObjectUtil.isEmpty(dto.getCountryId())) {
            return ResponseResult.error("Parameter Error!");
        }
        List<PharmacyGroupQueryByCountryIdVo> list = tblPharmacyGroupMapper.findListPharmacyGroupByCountryId(dto.getCountryId());
        return ResponseResult.success(list);
    }

    @Override
    public ResponseResult updateDispOrder(PharmacyDto dto) {
        if (ObjectUtil.isEmpty(dto.getDispOrder()) || ObjectUtil.isEmpty(dto.getId())){
            return ResponseResult.error("Parameter abnormality");
        }
        tblPharmacyMapper.updateDispOrder(dto);
        return ResponseResult.success();
    }
}
